<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\func\Tools;
use app\common\model\Balance;
use app\common\model\BalanceTotal;
use app\common\model\BalanceType;
use app\common\model\BankCard;
use app\common\model\Money;
use app\common\model\User;
use app\common\model\WithdrawalChannel;
use app\common\model\WithdrawalOrder;
use app\common\model\WithdrawalSetting;
use app\common\model\WithdrawalSettings;
use think\Db;
use zjkal\ChinaHoliday;

/**
 * 提现
 */
class Withdraw extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 提现状态
     */
    public function getWithdrawState()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $balance_type_id = $this->request->post('balance_type_id');
        $info = WithdrawalSetting::where('balance_type_id', $balance_type_id)->where('status', 1)->find();
        $this->success("请求成功", $info);
    }

    /**
     * 提现状态
     */
    public function getWithdrawStateNew()
    {
        $info = WithdrawalSettings::where('status', 1)->find();
        $this->success("请求成功", $info);
    }

    /**
     * 提现
     */
    public function withdrawCash()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $withdrawal_money = $this->request->post('withdrawal_money');

        $user = User::get($this->auth->id);
        if (empty($user)) {
            $this->error("系统错误，请联系管理员！");
        }

        if ($user->withdraw_state == 2) {
            $this->error("您暂时无法提现，请联系您的上级");
        }

        if (!$withdrawal_money) {
            $this->error("提现金额为空");
        }

        if (!ChinaHoliday::isWorkday()) {
            $this->error("请于工作日提现！");
        }

        $order_number = createOrderNumber();
        // 获取提现设置
        $withdrawal_setting = WithdrawalSettings::where('status', 1)->find()->toArray();
        if (!empty($withdrawal_setting)) {
            // 验证是否开启提现
            if ($withdrawal_setting["is_open"] == 2) {
                $this->error($withdrawal_setting["remarks"]);
            }
            // 提现 - 开始时间
            $start_time = strtotime(date('Y-m-d') . " " . $withdrawal_setting["withdrawal_start_time"]);
            // 提现 - 截止时间
            $end_time = strtotime(date('Y-m-d') . " " . $withdrawal_setting["withdrawal_end_time"]);
            // 当前时间
            $now_time = time();
            if ($start_time > $now_time || $end_time < $now_time) {
                $this->error("您好，请您于【" . $withdrawal_setting["withdrawal_start_time"] . " ~ " . $withdrawal_setting["withdrawal_end_time"] . "】这个时间段进行提现！");
            }
            // 验证提现次数
            if ($withdrawal_setting["withdrawal_number"] != 0) {
                $nowDate = date("Y-m-d");
                $withdrawal_number = WithdrawalOrder::where("FROM_UNIXTIME(create_time, '%Y-%m-%d') = '" . $nowDate . "'")
                    ->where(["main_type" => 2, "sale_id" => $this->auth->id])
                    ->where('status', 1)
                    ->fetchSql(true)
                    ->count();
                if ($withdrawal_number >= $withdrawal_setting["withdrawal_number"]) {
                    $this->error("抱歉，您已超单日提现次数，请明日继续！");
                }
            }
            // 验证提现金额
            $wmoney = $withdrawal_money * 10000;
            if ($wmoney < $withdrawal_setting["withdrawal_min_money"] * 10000) {
                $this->error("提现金额不得低于【" . $withdrawal_setting["withdrawal_min_money"] . "】");
            }
            if ($wmoney > $withdrawal_setting["withdrawal_max_money"] * 10000) {
                $this->error("提现金额不得高于【" . $withdrawal_setting["withdrawal_max_money"] . "】");
            }
            $tax_rate_money = bcmul($withdrawal_money, ($withdrawal_setting["tax_rate"] / 100), 2);
            $arrival_amount = bcsub(bcsub($withdrawal_money, $tax_rate_money, 2), $withdrawal_setting["service_charge"], 2);
            if ($arrival_amount * 100 < 0) {
                $this->error("提现金额不足支付手续费！");
            }
            // 获取余额
            $balane = Balance::where(["main_type" => 2, "main_id" => $this->auth->id])->value('money');
            if ($balane < $withdrawal_money) {
                $this->error("抱歉，您的余额不足！");
            }
            // 获取提现银行卡
            $bank_card = Db::name("bank_card")->where('status', 1)->where('sale_id', $this->auth->id)->find();
            if (empty($bank_card)) {
                $this->error("请您先绑定银行卡！");
            }
            $plat_balance = Cloudcomputing::balanceQuery();
            if ($plat_balance < $withdrawal_money * 100) {
                if (self::getSmsNum('18047140462')) {
                    sendSms(63, ($plat_balance / 100), 18047140462);
                }
                if (self::getSmsNum('15184764678')) {
                    sendSms(63, ($plat_balance / 100), 15184764678);
                }
                $this->error("提现正在维护，请稍后继续提现");
            }
            if ($withdrawal_setting["check_type"] == 2) {
                // 获取提现通道
                $withdrawal_channel = WithdrawalChannel::where('status', 1)->find();
                if (!empty($withdrawal_channel)) {
                    $cloudcomputingData = [
                        "enterprise_code" => $withdrawal_channel->enterprise_code,
                        "channel_code" => $withdrawal_channel->channel_code,
                        "task_code" => $withdrawal_channel->task_code,
                        "public_key" => $withdrawal_channel->public_key
                    ];
                } else {
                    $this->error("提现失败，请联系系统管理员！");
                }
            }
            // 验证订单
            $count = WithdrawalOrder::where('order_number', $order_number)->where('status', 1)->count();
            if ($count > 0) {
                $this->error("抱歉，提现发生错误，请重新提现！");
            }
            $tax_rate_money = bcmul($withdrawal_money, ($withdrawal_setting["tax_rate"] / 100), 2);
            $data = [
                "order_number" => $order_number,
                "company_id" => $this->auth->company_id,
                "main_type" => 2,
                "sale_id" => $this->auth->id,
                "withdrawal_money" => $withdrawal_money,
                "service_charge" => $withdrawal_setting["service_charge"],
                "tax_rate" => $withdrawal_setting["tax_rate"],
                "tax_rate_money" => $tax_rate_money,
                "arrival_amount" => bcsub(bcsub($withdrawal_money, $tax_rate_money, 2), $withdrawal_setting["service_charge"], 2),
                "before" => $balane,
                "after" => bcsub($balane, $withdrawal_money, 2),
                "name" => $bank_card["name"],
                "phone" => $bank_card["phone"],
                "idcards" => $bank_card["idcards"],
                "bank_card_number" => $bank_card["bank_card_number"],
                "create_time" => time()
            ];
            $res = WithdrawalOrder::create($data);
            if ($res) {
                if (Tools::saveBalance(2, $this->auth->id, $withdrawal_money, 1)) {
                    if ($withdrawal_setting["check_type"] == 2) {
                        $return = Cloudcomputing::singleWithdrawal($order_number, $cloudcomputingData);
                        if ($return["code"] != 200) {
                            self::ordervoid($order_number, $return["msg"]);
                            $this->error($return["msg"]);
                        } else {
                            WithdrawalOrder::where(["order_number" => $order_number])->update(
                                ["withdrawal_channel_id" => $withdrawal_channel["id"], "audit_status" => 2, "audit_time" => time()]
                            );
                        }
                    }
                    $this->success("提现成功！");
                } else {
                    $this->error("抱歉，系统错误，请重新提现！");
                }
            } else {
                $this->error("抱歉，提现发生错误，请重新提现！");
            }
        } else {
            $this->error("提现功能维护中，请联系系统管理员！");
        }
    }

    /**
     * 订单作废
     */
    public static function ordervoid($order_number, $msg)
    {
        $order = WithdrawalOrder::where('order_number', $order_number)->find();
        if (!empty($order)) {
            if ($order->status == 1 && $order->payment_status == 1) {
                $res = WithdrawalOrder::where('order_number', $order_number)->update(["status" => 2, "port_content" => $msg]);
                if ($res) {
                    Tools::saveBalance(2, $order->sale_id, $order->withdrawal_money, 2);
                }
            }
        }
    }

    public static function getSmsNum($phone = '18748149147') {
        $isTrue = true;
        $info = Db::name('sms_logs')->where(["sms_phone" => $phone])->where('sms_content', 'like', '%尊敬的客户，您的平台代付余额%')->order("sms_create_time desc")->find();
        if (!empty($info)) {
            $sendTime = strtotime('+1 hours', $info["sms_create_time"]);
            if ($sendTime < time()) {
                $isTrue = true;
            } else {
                $isTrue = false;
            }
        }
        return $isTrue;
    }

    /**
     * 提现记录
     */
    public function withdrawalRecord()
    {
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('page_size', 15);
        $fields = "order_number,balance_type_id,clearing_form,withdrawal_money,service_charge,tax_rate,tax_rate_money,arrival_amount,create_time,payment_status,payment_time,audit_status,audit_time,remarks,status";
        $list = WithdrawalOrder::where('sale_id', $this->auth->id)->field($fields)->order('create_time desc')->paginate($pageSize);
        foreach ($list as $row) {
            $row->balance_type_id = BalanceType::where('id', $row->balance_type_id)->value("name");
            $row->clearing_form = ($row->clearing_form == 1) ? "秒结算" : "月结算";
            $row->status_text = ($row->status == 1) ? "正常" : "作废";
            switch ($row->payment_status) {
                case 1:
                    $row->payment_status_text = "提现中";
                    $row->class_name = "warn_y";
                    break;
                case 2:
                    $row->payment_status_text = "提现成功";
                    $row->class_name = "green_y";
                    break;
                case 3:
                    $row->payment_status_text = "提现失败";
                    $row->class_name = "red_y";
                    break;
                default:
                    $row->payment_status_text = "提现中";
                    $row->class_name = "warn_y";
            }
            switch ($row->audit_status) {
                case 1:
                    $row->audit_status_text = "待审核";
                    break;
                case 2:
                    $row->audit_status_text = "已审核";
                    break;
                default:
                    $row->audit_status_text = "待审核";
            }
        }
        $this->success("请求成功", $list);
    }
}
